<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--科室数据-->
      <!-- <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input v-model="deptName" placeholder="请输入科室名称" clearable size="small" prefix-icon="el-icon-search"
            style="margin-bottom: 20px" />
        </div>
        <div class="head-container">
          <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false"
            :filter-node-method="filterNode" ref="tree" default-expand-all highlight-current
            @node-click="handleNodeClick" />
        </div>
      </el-col> -->
      <!--用户数据-->
      <el-col :span="24" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="60px" class="formBox formBox1 searchForm">
          <el-form-item label="医院" prop="hospital" clearable>
            <department :isHospital="true" :isdepat="true" @refreshData="refreshData" deptWidth="240px" ref="department">
            </department>
          </el-form-item>
          <el-form-item label="专病名称" prop="diseaseId">
            <el-select v-model="queryParams.diseaseId" placeholder="专病名称" clearable filterable style="width: 240px">
              <el-option v-for="dict in classifyList" :key="dict.diseaseClassifyId" :label="dict.diseaseClassifyName"
                :value="dict.diseaseClassifyId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="表单类型" prop="formType">
            <el-select v-model="queryParams.formType" placeholder="表单类型" clearable filterable style="width: 240px">
              <el-option v-for="dict in dict.type.sys_form_type" :key="dict.value" :label="dict.label"
                :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="表单名称" prop="formName">
            <el-input v-model="queryParams.formName" placeholder="请输入表单名称" clearable style="width: 240px"
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="表单状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="表单状态" clearable filterable style="width: 240px">
              <el-option v-for="dict in formStatusList" :key="dict.value" :label="dict.label"
                :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
              range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <div class="formBox searchForm"  ref="statisticalTable" style="margin-bottom:0px!important;">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
              v-hasPermi="['system:form:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
              v-hasPermi="['system:form:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="el-icon-plus" size="mini" @click="platformTempDialogVisible = true"
              v-hasPermi="['system:form:temp']">引入平台模板</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
                        <el-button
                            type="danger"
                            plain
                            icon="el-icon-delete"
                            size="mini"
                            :disabled="multiple"
                            @click="handleDelete"
                            v-hasPermi="['system:user:remove']"
                        >删除</el-button>
                    </el-col> -->
          <!-- <el-col :span="1.5">
                        <el-button
                            type="info"
                            plain
                            icon="el-icon-upload2"
                            size="mini"
                            @click="handleImport"
                            v-hasPermi="['system:user:import']"
                        >导入</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button
                            type="warning"
                            plain
                            icon="el-icon-download"
                            size="mini"
                            @click="handleExport"
                            v-hasPermi="['system:user:export']"
                        >导出</el-button>
                    </el-col> -->
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table border v-loading="loading" :data="formList" @selection-change="handleSelectionChange"
          :row-class-name="tableRowClassName" :height="statisticalTableH"  ref="table">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column sortable label="表单编号" align="center" key="formId" prop="formId" v-if="columns[0].visible"
            :width="100" />
          <!--          <el-table-column sortable label="表单序号" align="center" key="formSort" prop="formSort" v-if="columns[1].visible"-->
          <!--            :width="100" />-->
          <el-table-column sortable label="表单名称" align="center" key="formName" prop="formName" v-if="columns[2].visible"
            :show-overflow-tooltip="true" :width="240" />
          <el-table-column sortable label="表单类型" align="center" key="formType" prop="formType" v-if="columns[3].visible"
            :show-overflow-tooltip="true" :width="100">
            <template slot-scope="scope">
              <span>{{ matchDict("sys_form_type", scope.row.formType) }}</span>
            </template>
          </el-table-column>
          <el-table-column sortable label="专病名称" align="center" key="diseaseNames" prop="diseaseNames"
            v-if="columns[4].visible" :show-overflow-tooltip="true" :width="100">
          </el-table-column>

          <el-table-column label="医院" align="center" prop="hospitalName" :show-overflow-tooltip="true" width="150">
            <template slot-scope="scope">
              <departTag :options="deptNameLists" :value="scope.row.hospitalId" />
            </template>
          </el-table-column>
          <el-table-column label="科室" align="center" prop="deptName" :show-overflow-tooltip="true" width="150">
            <template slot-scope="scope">
              <departTag :options="deptNameLists" :value="scope.row.deptId" />
            </template>
          </el-table-column>
          <el-table-column sortable label="表单状态" align="center" key="status" v-if="columns[10].visible" :width="100">
            <template slot-scope="scope">
              <el-button v-if="scope.row.status === '2'" size="mini" type="text" icon="el-icon-video-play"
                @click="start(scope.row)">启用</el-button>
              <el-switch v-else v-model="scope.row.status" active-value="0" inactive-value="1"
                @change="handleStatusChange(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column sortable label="创建时间" align="center" prop="createTime" v-if="columns[5].visible" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column sortable label="表单用途" align="center" prop="purpose" v-if="columns[7].visible" :width="100">
            <template slot-scope="scope">
              <span>{{
                matchDict("sys_form_purpose", scope.row.purpose)
              }}</span>
            </template>
          </el-table-column>
          <el-table-column sortable label="科研项目" align="center" prop="research" v-if="columns[8].visible" :width="100">
            <template slot-scope="scope">
              <span>{{
                matchDict("sys_research_projects", scope.row.research)
              }}</span>
            </template>
          </el-table-column>
          <el-table-column sortable label="备注" align="center" prop="remark" v-if="columns[9].visible"
            :show-overflow-tooltip="true">
          </el-table-column>



          <el-table-column label="操作" align="center" width="220" fixed="right" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <!--              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"-->
              <!--                v-hasPermi="['system:user:edit']">修改</el-button>-->
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                v-show="scope.row.status === '2'" v-hasPermi="['system:form:remove']">删除</el-button>
              <el-button size="mini" type="text" icon="el-icon-view" @click="handlePreview(scope.row)"
                v-hasPermi="['system:form:preview']">预览</el-button>
              <el-button size="mini" type="text" icon="el-icon-document" @click="handleDetail(scope.row)"
                v-if="scope.row.status == '2'" v-hasPermi="['system:form:content']">表单内容</el-button>
              <el-button size="mini" type="text" icon="el-icon-document-copy" @click="copyForm(scope.row)" v-else
                v-hasPermi="['system:form:copy']">复制</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
          @pagination="getList" />
        </div>
      </el-col>
    </el-row>

    <!-- 添加或修改表单配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="表单名称" prop="formName">
              <el-input v-model="form.formName" placeholder="请输入表单名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-show="form.formType != 0">
          <el-col :span="24">
            <el-form-item label="适用专病" prop="diseaseIds">
              <el-select v-model="form.diseaseIds" placeholder="请选择适用专病" multiple filterable style="width: 470px">
                <el-option v-for="dict in classifyList" :key="dict.diseaseClassifyId" :label="dict.diseaseClassifyName"
                  :value="dict.diseaseClassifyId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="表单类型" prop="formType">
              <el-select v-model="form.formType" placeholder="表单类型" filterable clearable>
                <el-option v-for="dict in dict.type.sys_form_type" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="使用科室" prop="deptId" v-if="open">
              <department :isAdd="true" @changedepatData="changedepatData" :HospitalId="form.hospitalId" :Optiohospitals="true"
                :deptIds="form.deptId" :isdisabled="false">
              </department>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="表单用途" prop="purpose">
              <el-select v-model="form.purpose" placeholder="表单用途" filterable clearable>
                <el-option v-for="dict in dict.type.sys_form_purpose" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="对应科研库" prop="research">
              <el-select v-model="form.research" placeholder="对应科研库" filterable clearable>
                <el-option v-for="dict in dict.type.sys_research_projects" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!--        <el-row>-->
        <!--          <el-col :span="12">-->
        <!--            <el-form-item label="显示排序" prop="formSort">-->
        <!--              <el-input-number v-model="form.formSort" controls-position="right" />-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <!--        </el-row>-->
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否用于色斑平台" label-width="140px">
              <el-radio-group v-model="form.platformType">
                <el-radio v-for="dict in stainArr" :key="dict.value" :label="dict.value">{{ dict.label
                }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="填表说明" prop="remark">
              <el-input v-model="form.remark" type="textarea" rows="5" placeholder="请输入表单填表说明" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
                        <el-form-item label="表单状态">
                            <el-radio-group v-model="form.status">
                                <el-radio
                                    v-for="dict in dict.type.sys_normal_disable"
                                    :key="dict.value"
                                    :label="dict.value"
                                >{{dict.label}}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col> -->
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 表单预览 -->
    <el-dialog title="表单预览" :visible.sync="formPreviewOpen" width="1000px" append-to-body v-dialog-drag>
      <formpreview v-if="formpreviewContList != null" :formPreviewList="formpreviewContList"
        :questionFormInfo="questionFormInfo" />
    </el-dialog>
    <!-- 添加或修改表单内容配置对话框 -->
    <el-dialog :title="title" :visible.sync="formContOpen" width="1200px" append-to-body v-dialogDrag>
      <el-form ref="formCont" :model="formCont" :rules="formRules" label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="显示排序" prop="questionSort">
              <el-input-number v-model="formCont.questionSort" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="控件类型" prop="questionType">
              <el-select v-model="formCont.questionType" placeholder="控件类型" filterable clearable>
                <el-option v-for="dict in dict.type.sys_question_type" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否必填" prop="requiredFlag">
              <el-radio-group v-model="formCont.requiredFlag">
                <el-radio v-for="dict in dict.type.sys_form_must" :key="dict.value" :label="dict.value">{{ dict.label
                }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="问题标题" prop="questionName">
              <el-input v-model="formCont.questionName" placeholder="请输入问题" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-show="formCont.questionType != 3 && formCont.questionType != 4" v-for="item in answerJson"
          :key="item.id">
          <el-col :span="20">
            <el-form-item :label="'选项' + item.id" prop="answer">
              <el-input v-model="item.value" placeholder="请输入选项" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item>
              <el-button icon="el-icon-delete" size="mini" @click="delAnswer(item)"></el-button>
              <el-button v-show="item.status" icon="el-icon-circle-plus-outline" size="mini"
                @click="addAnswer"></el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="2" :offset="18" v-if="isNewAdd">
            <el-form-item>
              <el-button type="primary" size="mini" @click="newAddSubmit">新增提交</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="2" :offset="18" v-else>
            <el-form-item>
              <el-button type="primary" size="mini" @click="updateSubmit">修改提交</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item>
              <el-button type="primary" size="mini" @click="resetFormCont">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table :data="formContList">
        <el-table-column label="控件编号" align="center" key="questionId" prop="questionId" />
        <el-table-column label="显示排序" align="center" key="questionSort" prop="questionSort" />
        <el-table-column label="控件类型" align="center" key="questionType" prop="questionType" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{
              matchDict("sys_question_type", scope.row.questionType)
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="问题标题" align="center" key="questionName" prop="questionName" :width="300" />
        <el-table-column label="答案" align="center" :width="300">
          <template slot-scope="scope">
            <span v-html="getAnswerText(scope.row)"></span>
          </template>
        </el-table-column>
        <el-table-column label="是否必填" align="center" key="requiredFlag" prop="requiredFlag">
          <template slot-scope="scope">
            <span>{{
              matchDict("sys_form_must", scope.row.requiredFlag)
            }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column
                    label="创建时间"
                    align="center"
                    prop="createTime"
                    width="160"
                >
                    <template slot-scope="scope">
                        <span>{{ parseTime(scope.row.createTime) }}</span>
                    </template>
                </el-table-column> -->
        <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="updateFormContItem(scope.row)"
              v-hasPermi="['system:user:edit']">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="delFormContItem(scope.row)"
              v-hasPermi="['system:user:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="formContTotal > 0" :total="formContTotal" :page.sync="formContQueryParams.pageNum"
        :limit.sync="formContQueryParams.pageSize" @pagination="getFormContList" />
    </el-dialog>
    <!-- 表单导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />
            是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 引入平台模板 -->
    <el-dialog :title="platformTitle" :visible.sync="platformTempDialogVisible" v-dialogDrag width="90%"
      :close-on-click-modal="false">
      <platformTemp v-if="platformTempDialogVisible" @closeplatformTempDialogVisible="closeplatformTempDialogVisible"
        type="1" @refresh="refreshFormList">
      </platformTemp>
    </el-dialog>
  </div>
</template>

<script>
import department from "@/views/components/department/index.vue";
import departTag from "@/views/components/department/departTag.vue";
import platformTemp from "@/views/components/platformTemp/formTemp.vue";
import {
  getForm,
  listForm,
  addForm,
  updateForm,
  delForm,
  copyForm,
  changeFormStatus,
  addFormCont,
  updateFormCont,
  listFormCont,
  listQuestion,
  delFormCont,
} from "@/api/system/form";
import { deptNameList } from "@/api/system/dept";
import { deptTreeSelect } from "@/api/system/user";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import Formpreview from "@/views/system/form/Formpreview";
import { listClassify } from "@/api/system/classify";
export default {
  name: "formList",
  dicts: [
    "sys_normal_disable",
    "sys_manage_diseases",
    "sys_form_type",
    "sys_form_purpose",
    "sys_research_projects",
    "sys_question_type",
    "sys_form_must",
  ],
  components: { Treeselect, Formpreview, department, departTag, platformTemp },
  data() {
    return {
      statisticalTableH:undefined,
      platformTempDialogVisible: false,
      platformTitle: '平台模板-表单',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      formList: null,
      // 弹出层标题
      title: "",
      // 科室树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 科室名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      // 表单参数
      form: {
        roleIds: [],
        deptId: undefined,
        hospitalId: undefined,
        platformType: 0
      },
      stainArr: [{ value: 0, label: '否' }, { value: 1, label: '是' },],
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        status: undefined,
        diseaseId: undefined,
        formType: undefined,
        formName: undefined,
        deptId: undefined,
        hospitalId: undefined,
      },
      // 列信息
      columns: [
        { key: 0, label: `表单编号`, visible: true },
        { key: 1, label: `表单序号`, visible: true },
        { key: 2, label: `表单名称`, visible: true },
        { key: 3, label: `表单类型`, visible: true },
        { key: 4, label: `专病名称`, visible: true },
        { key: 5, label: `创建时间`, visible: true },
        { key: 6, label: `科室`, visible: true },
        { key: 7, label: `表单用途`, visible: true },
        { key: 8, label: `科研项目`, visible: true },
        { key: 9, label: `备注`, visible: true },
        { key: 10, label: `表单状态`, visible: true },
      ],
      // 表单校验
      rules: {
        deptId: [
          {
            required: true,
            message: "使用科室不能为空",
            trigger: "blur",
          },
        ],
        // diseaseId: [
        //     {
        //         required: true,
        //         message: "适用专病不能为空",
        //         trigger: "blur",
        //     },
        // ],
        // purpose: [
        //     {
        //         required: true,
        //         message: "表单用途不能为空",
        //         trigger: "blur",
        //     },
        // ],
        formType: [
          {
            required: true,
            message: "表单类型不能为空",
            trigger: "blur",
          },
        ],
        mName: [
          {
            required: true,
            message: "表单名称不能为空",
            trigger: "blur",
          },
          {
            min: 2,
            max: 20,
            message: "表单名称长度必须介于 2 和 20 之间",
            trigger: "blur",
          },
        ],
      },
      // 总条数
      formContTotal: 0,
      // 查询参数
      formContQueryParams: {
        pageNum: 1,
        pageSize: 10,
        formId: undefined,
      },
      formContList: null,
      formpreviewContList: null,
      formInfo: {},
      questionFormInfo: {
        name: "",
        remark: "",
      },
      formContOpen: false,
      formCont: {
        formId: undefined,
        options: "",
        questionSort: undefined,
        questionType: undefined,
        questionName: undefined,
        requiredFlag: undefined,
      },
      formRules: {
        questionType: [
          {
            required: true,
            message: "请选择控件类型",
            trigger: "blur",
          },
        ],
        requiredFlag: [
          {
            required: true,
            message: "请选择是否必填",
            trigger: "blur",
          },
        ],
        questionName: [
          {
            required: true,
            message: "表单名称不能为空",
            trigger: "blur",
          },
        ],
      },
      answerJson: [{ id: 1, value: "", status: true }],
      formPreviewOpen: false,
      isNewAdd: true,
      formStatusList: [
        { value: "0", label: "已启用" },
        { value: "1", label: "已停用" },
        { value: "2", label: "待启用" },
      ],
      isClickBtnStatus: false,
      classifyList: [],
      deptNameLists: []
    };
  },

  created() {
    this.getClassifyList();
    // this.getList();
    // this.getDeptTree();
    this.getConfigKey("sys.user.initPassword").then((response) => {
      this.initPassword = response.msg;
    });
  },
  mounted() {
   this.changeHeight()
  },
  watch: {
    // 根据名称筛选科室树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
    showSearch() {
      this.$nextTick(() => {
        this.changeHeight()
      }, 1000)

    }
  },
  updated() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  computed: {
    doctorRoleShow: function () {
      return this.form.roleIds.includes(101);
    },
  },
  methods: {
    changeHeight() {
      if (this.$refs.statisticalTable) {
        const statisticalTableObj = this.$refs.statisticalTable.getBoundingClientRect();
        let h = statisticalTableObj.top + 100
        this.statisticalTableH = 'calc(100vh - ' + h + 'px)'
      } else {
        this.statisticalTableH = '500px'
      }
    },
    closeplatformTempDialogVisible() {
      this.platformTempDialogVisible = false
    },
    refreshData(data) {
      this.queryParams.pageNum = 1;
      this.queryParams.hospitalId = data.hospitalId
      this.queryParams.deptId = data.deptId
      this.getdeptNameList();

    },
    changedepatData(data) {
      if (data && data.length > 0) {
        this.form.deptId = data[0].deptId
        this.form.hospitalId = data[0].parentId==100?data[0].deptId:data[0].parentId
      } else {
        this.form.deptId = undefined
        this.form.hospitalId = undefined
      }
    },
    // 回显医院及门诊
    getdeptNameList() {
      deptNameList().then((response) => {
        console.log(response.data)
        this.deptNameLists = response.data;
        this.getList();
      });
    },
    getClassifyList() {
      listClassify({ pageNum: 1, pageSize: 9999 }).then((response) => {
        this.classifyList = response.rows;
      });
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex === 0 && this.isClickBtnStatus) {
        return "success-row";
      } else {
        return "";
      }
    },
    getAnswerText(row) {
      if (row.questionType != 3 || row.questionType != 4) {
        let text = "";
        if (typeof row.options === "string") {
          JSON.parse(row.options).forEach((item) => {
            text += item.id + ":" + item.value + "</br>";
          });
        } else {
          row.options.forEach((item) => {
            text += item.id + ":" + item.value + "</br>";
          });
        }
        return text;
      }
    },
    resetFormCont() {
      this.resetForm("formCont");
      this.answerJson = [{ id: 1, value: "", status: true }];
      this.isNewAdd = true;
    },
    /** 修改表单内容控件列表 */
    updateFormContItem(row) {
      Object.keys(row).forEach((key) => {
        this.formCont[key] = row[key];
      });
      if (row.questionType != 3 || row.questionType != 4) {
        this.answerJson = JSON.parse(row.options);
      }
      this.isNewAdd = false;
    },
    /** 删除表单内容控件列表 */
    delFormContItem(row) {
      const questionId = row.questionId;
      this.$modal
        .confirm('是否确认删除控件编号为"' + questionId + '"的数据项？')
        .then(function () {
          return delFormCont(questionId);
        })
        .then(() => {
          this.getFormContList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 查询表单内容控件列表 */
    getFormContList() {
      listQuestion(this.formContQueryParams).then((response) => {
        this.formContList = response.rows;
        this.formpreviewContList = response.rows;
        this.formpreviewContList.forEach((item) => {
          if (item.questionType === "2") {
            this.$set(item, "answer", []);
          } else {
            this.$set(item, "answer", null);
          }
        });
        this.formContTotal = response.total;
      });
    },
    /** 查询表单内容所有控件列表 */
    getAllFormContList(row) {
      listFormCont({
        formId: row.formId,
      }).then((response) => {
        this.questionFormInfo.name = response.name;
        this.questionFormInfo.remark = response.remark;
        this.formContList = response.rows;
        this.formpreviewContList = response.rows;
        this.formpreviewContList.forEach((item) => {
          if (item.questionType === "2") {
            this.$set(item, "answer", []);
          } else {
            this.$set(item, "answer", null);
          }
        });
      });
    },
    /** 新增提交 */
    newAddSubmit() {
      this.$refs["formCont"].validate((valid) => {
        if (valid) {
          this.formCont.options = JSON.stringify(this.answerJson);
          addFormCont(this.formCont).then((response) => {
            this.$modal.msgSuccess("新增成功");
            this.resetForm("formCont");
            this.answerJson = [{ id: 1, value: "", status: true }];
            this.getFormContList();
          });
        }
      });
    },
    updateSubmit() {
      this.$refs["formCont"].validate((valid) => {
        if (valid) {
          this.formCont.options = JSON.stringify(this.answerJson);
          updateFormCont(this.formCont).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.getFormContList();
          });
        }
      });
    },
    /** 增加选项 */
    addAnswer() {
      const idNum = this.answerJson.at(-1).id + 1;
      /**增加按钮只有id最大时显示 */
      this.answerJson.forEach((item) => {
        if (item.id < idNum) {
          item.status = false;
        }
      });
      this.answerJson.push({ id: idNum, value: "", status: true });
    },
    /** 删除选项 */
    delAnswer(row) {
      if (this.answerJson.length === 1) {
        this.$message.warning("至少要有一个选项");
        return;
      }

      const idNum = this.answerJson.at(-1).id;
      /**如果点击删除的元素刚好是id最大的,那直接删除最后一个元素 */
      if (row.id === idNum) {
        this.answerJson = this.answerJson.slice(0, -1);
        this.answerJson.forEach((item) => {
          if (item.id < idNum - 1) {
            item.status = false;
          } else {
            item.status = true;
          }
        });
        this.$forceUpdate();
      } else {
        /**如果点击删除的元素不是id最大的 */
        this.answerJson = this.answerJson.filter((item) => {
          return item.id != row.id;
        });
        let id = 0;
        this.answerJson.forEach((item) => {
          id += 1;
          item.id = id;
        });
      }
    },
    /** id转化成对应的文字 */
    matchDict: function (key, id) {
      let _this = this;
      const result = _this.dict.type[key];
      let textValue = "";
      result.forEach((item) => {
        if (item.raw.dictValue == id) {
          textValue = item.raw.dictLabel;
        }
      });
      return textValue;
    },
    /** 平台模板引用或者批量引用点击后关闭弹窗并刷新本院表单列表 */
    refreshFormList() {
      this.platformTempDialogVisible = false
      this.getList()
    },
    /** 查询表单列表 */
    getList() {
      this.loading = true;
      listForm(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.formList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    /** 查询科室下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.handleQuery();
    },
    // 启用表单 启用后不可修改表单内的控件
    start(row) {
      let that = this;
      changeFormStatus(row.deptId, row.formId, "0").then((res) => {
        //signcode存在则表明通用表已存在
        if (!!res.signcode) {
          this.$modal
            .confirm(res.msg + "并且开启《" + row.formName + "》")
            .then(function () {
              changeFormStatus(res.data.hospitalId, res.data.formId, "1").then((result) => {
                that.$modal.msgSuccess("表单" + res.data.formId + "停用成功");
                changeFormStatus(row.hospitalId, row.formId, "0").then(() => {
                  that.$modal.msgSuccess("表单" + row.formId + "启用成功");
                  that.getList();
                });
              });
            });
        } else if (res.code === 200) {
          this.$modal
            .confirm(
              "表单一旦启用就不可编辑修改也不能删除，只能复制，是否确定启用？"
            )
            .then(function () {
              that.getList();
              that.$modal.msgSuccess("启用成功");
            });
        }
      });
      // this.$modal
      //     .confirm("确认要启用表单吗？一旦启用表单内的控件不可修改!")
      //     .then(function () {
      //         return changeFormStatus(row.formId, "0");
      //     })
      //     .then(() => {
      //         this.getList();
      //         this.$modal.msgSuccess("启用成功");
      //     }).catch(function (res) {
      //         console.log(res.error)
      //     });
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      if (row.status === "0") {
        this.start(row);
      } else {
        changeFormStatus(row.hospitalId, row.formId, row.status)
          .then(() => {
            this.$modal.msgSuccess(text + "成功");
          })
          .catch(function () {
            row.status = row.status === "0" ? "1" : "0";
          });
      }
      // this.$modal
      //     .confirm('确认要"' + text + '""' + row.formId + '"表单吗？')
      //     .then(function () {
      //          return changeFormStatus(row.formId, row.status);
      //     })
      //     .then(() => {
      //         this.$modal.msgSuccess(text + "成功");
      //     })
      //     .catch(function () {
      //         row.status = row.status === "0" ? "1" : "0";
      //     });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        formId: undefined,
        diseaseIds: [],
        formType: undefined,
        formName: undefined,
        deptId: undefined,
        status: "0",
        platformType: 0
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      if (this.$refs.department) {
        this.$refs.department.reset()
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.formId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleResetPwd":
          this.handleResetPwd(row);
          break;
        case "handleAuthRole":
          this.handleAuthRole(row);
          break;
        default:
          break;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加表单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const formId = row.formId || this.ids;
      getForm(formId).then((response) => {
        let data=response.data;
        this.form = response.data;
        if (data.platformType == undefined || data.platformType == null || data.platformType == '') {
             this.form.platformType = 0
         }
        this.open = true;
        this.title = "修改表单";
      });
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
      })
        .then(({ value }) => {
          resetUserPwd(row.formId, value).then((response) => {
            this.$modal.msgSuccess("修改成功，新密码是：" + value);
          });
        })
        .catch(() => { });
    },
    /** 分配角色操作 */
    handleAuthRole: function (row) {
      const formId = row.formId;
      this.$router.push("/system/user-auth/role/" + formId);
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.formId != undefined) {
            updateForm(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.status = "2";
            addForm(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const formIds = row.formId || this.ids;
      this.$modal
        .confirm("是否确认删除表单名称为《" + row.formName + "》的数据项？")
        .then(function () {
          return delForm(formIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 复制表单按钮操作 */
    copyForm(row) {
      const formIds = row.formId || this.ids;
      this.$modal
        .confirm("是否复制表单名称为《" + row.formName + "》的数据项？")
        .then(function () {
          return copyForm(formIds);
        })
        .then(() => {
          this.isClickBtnStatus = true;
          this.getList();
          this.$modal.msgSuccess("复制成功");
        })
        .catch(() => { });
    },
    /** 表单按钮操作 */
    handleDetail(row) {
      this.formContOpen = true;
      this.formContQueryParams.formId = row.formId;
      this.formCont.formId = row.formId;
      this.getFormContList();
    },
    /** 表单预览操作 */
    async handlePreview(row) {
      console.log("handlePreview", row);
      this.formPreviewOpen = true;
      this.formContQueryParams.formId = row.formId;
      this.formCont.formId = row.formId;
      this.formInfo = row;
      await this.getAllFormContList(row);
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/user/export",
        {
          ...this.queryParams,
        },
        `user_${new Date().getTime()}.xlsx`
      );
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "system/user/importTemplate",
        {},
        `user_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg +
        "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  },
};
</script>
<style scoped>
.el-dialog {
  font-size: 16px;
}

::v-deep .el-dialog {
  margin-top: 0 !important;
}

::v-deep .el-dialog .el-dialog__header {
  text-align: left;
  /*font-weight: bold;*/
  border-bottom: 1px solid #f3a4a1;
  padding-bottom: 0px;
}

::v-deep .el-dialog .el-dialog__header .el-dialog__title {
  color: #f3a4a1;
  line-height: 34px;
  display: inline-block;
}

::v-deep .el-dialog .el-dialog__header .el-dialog__title::after {
  content: "";
  display: block;
  height: 3px;
  background-color: #f3a4a1;
}

::v-deep .el-input-number--medium {
  width: 190px;
  line-height: 34px;
}

::v-deep .el-table .success-row {
  background: #f0f9eb;
}
</style>
